package com.google.code.fluentjoiner.jdbc;

import com.google.common.collect.ImmutableMap;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JDBCUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(JDBCUtils.class);

    public static void closeQuietly(final Connection connection)
    {
        if (connection != null)
        {
            try
            {
                connection.close();
            }
            catch(final Throwable throwable)
            {
                LOGGER.error("Throwable thrown when attempting to close a Connection.", throwable);
            }
        }
    }

    public static void closeQuietly(final Statement statement)
    {
        if (statement != null)
        {
            try
            {
                statement.close();
            }
            catch(final Throwable throwable)
            {
                LOGGER.error("Throwable thrown when attempting to close a Statement.", throwable);
            }
        }
    }

    public static void closeQuietly(final ResultSet resultSet)
    {
        if (resultSet != null)
        {
            try
            {
                resultSet.close();
            }
            catch(final Throwable throwable)
            {
                LOGGER.error("Throwable thrown when attempting to close a ResultSet.", throwable);
            }
        }
    }

    public static ImmutableMap<Integer, String> getColumnNames(final ResultSetMetaData resultSetMetaData) throws SQLException
    {
        final ImmutableMap.Builder<Integer, String> columnNameBuilder = ImmutableMap.builder();
        for (int count = 1; count <= resultSetMetaData.getColumnCount(); count++)
        {
            columnNameBuilder.put(count, resultSetMetaData.getColumnName(count));
        }
        return columnNameBuilder.build();
    }
}
